/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: am8.8.one.c
> Author:
> Mail: 
> Created Time: Wed 07 Aug 2024 08:22:46 PM PDT
***************************************************/

//定义一个全局变量，创建两个线程，对这个全局变量实现加1操作
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex;
int a=0;
void *fun (void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex); //加锁
		a = a+1;
		printf("a = %d\n",a);
	}
		pthread_mutex_unlock(&mutex); //释放锁
		sleep(1);
	}

}

int main(int argc,const char* argv[])
{
	pthread_t tid = 0,tid1 = 0;;
	int ret = 0;
	pthread_mutex_init(&mutex,NULL); //创建并初始化锁
	ret = pthread_create(&tid,NULL,fun,NULL);
	if(ret != 0)
	{
		perror("pthreah_create");
	}

	ret = pthread_create(&tid1,NULL,fun,NULL);
	if(ret != 0)
	{
		perror("pthreah_create");
	}
	pthread_join(tid,NULL);
	pthread_join(tid1,NULL);
	pthread_mutex_destroy(&mutex); //销毁锁
	return 0;
}
